<template>
  <div class="groups-tree">
    <a-tree
      v-model="checkedKeys"
      :auto-expand-parent="autoExpandParent"
      :expanded-keys="expandedKeys"
      :selected-keys="selectedKeys"
      :tree-data="treeData"
      @expand="onExpand"
      @select="onSelect"
      v-if="treeData.length>0"
    >
      <template slot="custom" slot-scope="item">
        <span> {{ item.title }}
          <span v-if="item.num">（{{ item.num }}）</span>
          <!--length-1，不包含当前节点//-->
          <!-- <span v-if="item.children.length>0">
            （{{ item.childrenKeys.length-1}}）
          </span> -->
        </span>
        <a-dropdown style="position: absolute; right: 10px;">
          <a class="ant-dropdown-link" @click="e => e.preventDefault()">
            <a-icon type="dash" style="transform: rotate(90deg);color: #000" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item key="0" @click="addGroups(item)">
              <a>新建下级群组</a>
            </a-menu-item>
            <a-menu-item @click="editGroups(item)">
              <a>修改群组名称</a>
            </a-menu-item>
            <a-menu-item @click="deleteGroups(item)">删除群组</a-menu-item>
          </a-menu>
        </a-dropdown>
      </template>
    </a-tree>
    <a-empty :image="simpleImage" v-else>
      <span slot="description"> 还未创建群组</span>
    </a-empty>
    <a-button block style="width: 94%; margin: 10px 3% 0;" @click="addGroups()">
      <a-icon type="plus" />
    </a-button>
    <groups-handke-modal :title="groupsModalTitle" @ok="modalOk" ref="groupsModalRef" />
  </div>
</template>

<script>
var setSlot = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    arr[i].scopedSlots = {
      title: 'custom',
    }
    arr[i].childrenKeys = getChild(arr, arr[i].key, []) //获取某节点的所有子节点（包含当前key至所有children的key值）
    if (arr[i].children && arr[i].children.length > 0) {
      setSlot(arr[i].children)
    }
  }
  return arr
}
var getChild = (nodes, item, arr) => {
  for (let el of nodes) {
    if (el.key === item) {
      arr.push(el.key);
      if (el.children) {
        childNodesDeep(el.children, arr);
      }
    } else if (el.children) {
      getChild(el.children, item, arr);
    }
  }
  return arr;
}
var childNodesDeep = (nodes, arr) => {
  if (nodes)
  nodes.forEach((ele) => {
    arr.push(ele.key);
    if (ele.children) {
      childNodesDeep(ele.children, arr);
    }
  });
}
import { Empty } from 'ant-design-vue';
import groupsHandkeModal from './groupsHandkeModal'
import * as peopleApi from '@/api/wxSmuggle/people.js'
export default {
  name: 'groupsTree',
  components: {
    groupsHandkeModal
  },
  data() {
    return {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      groupsModalTitle: null
    }
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  created() {
    this.initTree()
  },
  watch: {
    checkedKeys(checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.$emit('checkedKeys', checkedKeys)
    }
  },
  methods: {
    initTree() {
      peopleApi.labelTree({labelType: 2}).then(res => {
        if (res.success) {
          let datas = res.result
          // this.treeData = setSlot(this.treeData)
          this.treeData = setSlot(datas)
          this.$emit('tree', this.treeData)
          for (let i = 0; i < this.treeData.length; i++) {
            let temp = this.treeData[i]
            this.setThisExpandedKeys(temp)
          }
        }
      })
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.expandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys);
      this.checkedKeys = checkedKeys;
      this.$emit('checkedKeys', checkedKeys);
    },
    onSelect(selectedKeys, info) {
      console.log('onSelect', selectedKeys)
      this.selectedKeys = selectedKeys
      this.$emit('selectedKeys', selectedKeys)
    },
    //新建群组、新建下级群组
    addGroups(item) {
      if (item) {
        this.groupsModalTitle = '新建下级群组'
        const { dataRef } = item
        this.$refs.groupsModalRef.add(dataRef);
      } else {
        this.groupsModalTitle = '新建群组'
        this.$refs.groupsModalRef.add();
      }
    },
    editGroups(item) {
      const { dataRef } = item
      this.groupsModalTitle = '修改群组名称'
      if(this.$refs && this.$refs.groupsModalRef) {
        this.$refs.groupsModalRef.edit(dataRef);
      }
    },
    deleteGroups(item) {
      let that = this
      const { dataRef } = item
      let obj = {
        id: dataRef.key
      }
      that.$confirm({
        title: `确定删除“${dataRef.title}”?`,
        okType: 'danger',
        onOk() {
          peopleApi.labelTreeDelete(obj).then(res => {
            if (res.success) {
              that.$message.success(res.message)
              that.initTree()
            } else {
              that.$message.warn(res.message)
            }
          }).catch(e => {
            that.$message.warn('操作失败！')
          })
        },
        onCancel() {
          console.log('Cancel');
        }
      })
    },
    // 操作分组成功的回调
    modalOk() {
      this.initTree()
    }
  }
}
</script>
<style lang="less" scoped>
.groups-tree {
  padding-bottom: 10px;
  min-height: 600px;
  .ant-tree {
    border:1px #e8e8e8 solid;
    position: relative;
    // /deep/li {
    //   // padding: 0;
    //    &::before {
    //     content: '';
    //     position: absolute;
    //     left: 0;
    //     right: 0;
    //     // height: 4px;
    //     border-top: 1px #e8e8e8 solid;
    //   }
    // }
    // /deep/.ant-tree-child-tree > li {
    //   &:first-child {
    //     // padding: 0;
    //   }
    // }
  }
}
</style>
